package controller

import (
	"we-account-api/model"
	"we-account-api/pkg/base"
	"we-account-api/pkg/jwt"
	"we-account-api/pkg/response"
	"we-account-api/service"

	"github.com/gin-gonic/gin"
)

type WechatController struct {
	base.Controller
}

var Wechat = new(WechatController)

type WXLoginRequest struct {
	Code string `json:"code" binding:"required"`
}

func (c *WechatController) Login(ctx *gin.Context) {
	var req WXLoginRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		response.Error(ctx, "参数错误")
		return
	}

	wxResp, err := service.WechatService.Code2Session(req.Code)
	if err != nil {
		response.Error(ctx, "微信登录失败")
		return
	}

	// 查找或创建用户
	user := &model.User{
		OpenID:  wxResp.OpenID,
		UnionID: wxResp.UnionID,
	}

	if err := service.UserService.FindOrCreate(user); err != nil {
		response.Error(ctx, "用户创建失败")
		return
	}

	// 生成 JWT token
	token, err := jwt.GenerateToken(user.ID)
	if err != nil {
		response.Error(ctx, "token生成失败")
		return
	}

	response.Success(ctx, gin.H{
		"token": token,
		"user":  user,
	})
}
